package com.hunter.view;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;

import com.hunter.util.ConfigManager;
import com.hunter.util.HistoryUtil;
import com.hunter.util.LogUtil;
import com.hunter.util.PropertiesUtil;
import com.hunter.util.SystemUtil;
import com.mkk.swing.SwingUtil;
import com.mkk.swing.SwingUtil.UIType;

/**
 * 2010-8-31 下午10:56:22<br>
 * 程序主界面
 * 
 * @author mkk
 */
public class MainFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	public MainFrame() {
		main = this;
		// init
		this.initComponents();
		// events
		this.processEvents();
		// show
		this.showMe();
	}

	/**
	 * 初始化组件
	 */
	private void initComponents() {
		// tray
		this.initTrayCompents();
		// north
		this.add(this.showNorthPanel(), BorderLayout.NORTH);
		// center
		panel1 = new JPanel();
		this.cardLayout = new CardLayout();
		panel1.setLayout(cardLayout);
		// 添加主界面
		mainPanel = new MainPanel(this);
		panel1.add(mainPanel, MAIN_PANEL_NAME);
		this.add(panel1, BorderLayout.CENTER);
		// more panel if have
		// south
		this.add(this.showSouthPanel(), BorderLayout.SOUTH);
	}

	/**
	 * 显示北面面板信息
	 * 
	 * @return
	 */
	private JPanel showNorthPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		panel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
		this.label1 = new JLabel("[设置]");
		this.label1.setForeground(Color.BLUE);
		this.label1.setToolTipText("设置");
		this.label1.setCursor(new Cursor(Cursor.HAND_CURSOR));
		panel.add(this.label1);
		this.label3 = new JLabel("[首页]");
		this.label3.setToolTipText("首页");
		this.label3.setForeground(Color.BLUE);
		this.label3.setCursor(new Cursor(Cursor.HAND_CURSOR));
		this.label3.setVisible(false);
		panel.add(this.label3);
		return panel;
	}

	/**
	 * 南边界面
	 * 
	 * @return
	 */
	private JPanel showSouthPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
		panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		this.label2 = new JLabel();
		this.setInfo("欢迎使用 Hunter 1.0", Color.BLACK);
		panel.add(this.label2);
		panel.add(Box.createHorizontalStrut(490));
		this.jProgressBar1 = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
		this.jProgressBar1.setVisible(false);
		panel.add(this.jProgressBar1);

		return panel;
	}

	public JProgressBar getjProgressBar1() {
		return jProgressBar1;
	}

	/**
	 * 设置状态栏显示的信息
	 * 
	 * @param info
	 * @param c
	 */
	void setInfo(String info, Color c) {
		this.label2.setText(info);
		this.label2.setForeground(c);
	}

	/**
	 * 初始化系统托盘组件
	 */
	private void initTrayCompents() {
		if (SystemTray.isSupported()) {
			this.sTray = SystemTray.getSystemTray();
			// 图标
			Image image = SystemUtil.getSystemLogoIcon().getImage();
			// 菜单
			PopupMenu pm = new PopupMenu();
			MenuItem item = new MenuItem("Open");
			item.setActionCommand("open");
			item.addActionListener(this.getTrayActionListener());
			pm.add(item);
			pm.addSeparator();
			item = new MenuItem("Exit");
			item.setActionCommand("close");
			item.addActionListener(this.getTrayActionListener());
			pm.add(item);
			// create
			this.tIcon = new TrayIcon(image, PropertiesUtil.TITLE, pm);
			tIcon.addActionListener(this.getTrayActionListener());
			tIcon.addMouseListener(this.getTrayMouseListener());
			try {
				// add
				this.sTray.add(tIcon);
			} catch (AWTException ex) {
				LogUtil.saveExceptionLog(ex);
				SwingUtil.showErrorInfo(main, "警告", "警告: 该操作系统平台不支持系统托盘");
			}

		}
	}

	/**
	 * 系统托盘点击事件
	 * 
	 * @return
	 */
	private MouseListener getTrayMouseListener() {
		return new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int b = e.getButton();
				if (b == MouseEvent.BUTTON1) {
					if (e.getClickCount() == 1) {
						// dispose autocomplete window
						mainPanel.disposeWindow();
						if (!main.isVisible()) {
							main.setVisible(true);
							main.setExtendedState(JFrame.NORMAL);
						} else {
							main.setVisible(false);
						}
					}
				}
			}
		};
	}

	/**
	 * 系统托盘菜单点击事件
	 * 
	 * @return
	 */
	private ActionListener getTrayActionListener() {
		return new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				String command = e.getActionCommand();
				if ("open".equalsIgnoreCase(command)) {
					// 显示并正常化显示
					if (!main.isVisible()) {
						main.setVisible(true);
						main.setExtendedState(JFrame.NORMAL);
						// Dispose window
						mainPanel.disposeWindow();
					}
				} else if ("close".equalsIgnoreCase(command)) {
					existActions();
					System.exit(0);
				}
			}
		};
	}

	/**
	 * 关闭时的界面
	 * 
	 * @return
	 */
	private JPanel closePanel() {
		JPanel p = new JPanel();
		p.setLayout(new BorderLayout());
		JLabel l = new JLabel("选择关闭操作:");
		l.setForeground(Color.GRAY);
		p.add(l, BorderLayout.NORTH);
		JPanel p2 = new JPanel();
		ButtonGroup bg = new ButtonGroup();
		radioButton1 = new JRadioButton("退出系统");
		radioButton1.setSelected(true);
		radioButton2 = new JRadioButton("最小化到系统托盘");
		bg.add(radioButton1);
		bg.add(radioButton2);
		p2.add(radioButton1);
		p2.add(radioButton2);
		p.add(p2, BorderLayout.CENTER);
		checkBox1 = new JCheckBox("下次关闭时不再提示");
		checkBox1.setForeground(Color.GRAY);
		p.add(checkBox1, BorderLayout.SOUTH);
		return p;
	}

	/**
	 * 事件处理
	 */
	private void processEvents() {
		// 窗口事件
		this.addWindowListener(new WindowAdapter() {
			// 关闭窗口时
			@Override
			public void windowClosing(WindowEvent e) {
				// 若操作系统不支持系统托盘则直接关闭
				if (!SystemTray.isSupported()) {
					existActions();
					System.exit(0);
				}
				if (PropertiesUtil.isShowClosePanel()) {
					int i = SwingUtil.showConfirmInfo(main, "退出", closePanel());
					if (i == JOptionPane.OK_OPTION) {
						PropertiesUtil.setShowClosePanel(!checkBox1
								.isSelected());
						if (radioButton1.isSelected()) {
							try {
								PropertiesUtil.setCloseChooser(true);
								existActions();
							} finally {
								// no matter what happened,you must exit!!!
								System.exit(0);
							}
						}
						if (radioButton2.isSelected()) {
							PropertiesUtil.setCloseChooser(false);
							main.setVisible(false);
						}

					}
				} else {
					// 不显示则根据其选择的操作来处理
					if (PropertiesUtil.getCloseChooser()) {
						// 关闭
						try {
							existActions();
						} finally {
							// no matter what happened,you must exit!!!
							System.exit(0);
						}
					} else {
						// dispose autocomplete window
						mainPanel.disposeWindow();
						// 最小化到系统托盘
						main.setVisible(false);
					}
				}
			}

			// 最小化时
			@Override
			public void windowIconified(WindowEvent e) {
				// dispose autocomplete window
				mainPanel.disposeWindow();
				main.setVisible(false);
			}
		});
		// 移动事件
		this.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentMoved(ComponentEvent e) {
				// dispose autocomplete window
				mainPanel.disposeWindow();
			}
		});
		// 设置按钮事件
		this.label1.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				setInfo("设置您的搜索习惯", Color.BLACK);
			}

			public void mouseExited(MouseEvent e) {
				setInfo("欢迎使用 Hunter 1.0", Color.BLACK);
			}

			public void mouseClicked(MouseEvent e) {
				// 弹出设置界面
				EventQueue.invokeLater(new Runnable() {

					public void run() {
						// Dispose window
						mainPanel.disposeWindow();
						if (setDialog == null) {
							setDialog = new SettingDialog(main, true);
							Point p = SwingUtil.getStartPoint(setDialog
									.getWidth(), setDialog.getHeight());
							setDialog.setLocation(p);
						}
						setDialog.setVisible(true);
					}
				});
			}
		});

		// 回首页事件
		this.label3.addMouseListener(new MouseAdapter() {

			public void mouseEntered(MouseEvent e) {
				setInfo("返回桌面搜索主界面", Color.BLACK);
			}

			public void mouseExited(MouseEvent e) {
				setInfo("欢迎使用 Hunter 1.0", Color.BLACK);
			}

			public void mouseClicked(MouseEvent e) {
				// Dispose window
				mainPanel.disposeWindow();
				cardLayout.show(panel1, MAIN_PANEL_NAME);
				label3.setVisible(false);
				if (mainPanel != null) {
					mainPanel.getTextfield1().requestFocus();
				}
			}
		});

	}

	/**
	 * If have any action when exist system,please add in here
	 */
	private void existActions() {
		// Close search
		ConfigManager.getManager().close();
		// Save search keywords
		HistoryUtil.getHistoryUtil().persistenceKeywods();
	}

	/**
	 * @return the label3
	 */
	public JLabel getLabel3() {
		return label3;
	}

	/**
	 * @return the setDialog
	 */
	public SettingDialog getSetDialog() {
		return setDialog;
	}

	/**
	 * 获取中间面板布局管理器对象
	 * 
	 * @return
	 */
	public CardLayout getCardLayout() {
		return cardLayout;
	}

	/**
	 * 获取界面中间面板对象
	 * 
	 * @return
	 */
	public JPanel getPanel1() {
		return panel1;
	}

	/**
	 * 显示
	 */
	private void showMe() {
		this.setTitle(PropertiesUtil.TITLE);
		this.setIconImage(SystemUtil.getSystemLogoIcon().getImage());
		this.setSize(PropertiesUtil.DEFAULT_WIDTH,
				PropertiesUtil.DEFAULT_HEIGHT);
		Point p = SwingUtil.getStartPoint(this.getWidth(), this.getHeight());
		this.setLocation(p);
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.setVisible(true);
	}

	// 自身变量
	private MainFrame main;
	// 系统托盘相关
	private TrayIcon tIcon;
	private SystemTray sTray;
	private JCheckBox checkBox1;
	private JRadioButton radioButton1;
	private JRadioButton radioButton2;
	// 首选项标签
	private JLabel label1;
	// 中间面板对象
	private JPanel panel1;
	// 状态栏
	private JLabel label2;
	// 进度条
	private JProgressBar jProgressBar1;
	// 回首页
	private JLabel label3;
	// cardLayout
	private CardLayout cardLayout;
	// mainpanel
	private MainPanel mainPanel;
	// mainPanel name
	public static final String MAIN_PANEL_NAME = "mainPanel";
	// searchPanel name
	public static final String SEARCH_PANEL_NAME = "searchPanel";
	// setting dialog
	private SettingDialog setDialog;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				SwingUtil.setUI(UIType.WINDOWS);
				new MainFrame();
			}
		});
	}
}
